package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成html页面
 *
 * @Name : CreateHtmlTask
 * @Author : WuQiang
 * @Date : 2022-10-13 20:19
 * @Description : 生成html页面
 */
@Component
@Slf4j
public class CreateHtmlTask {
    @Autowired
    private Configuration configuration;
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private MinIOService minIOService;

    @Async
    public void createrHtml(ApArticle article, String content) {
        try {
            log.info("当前线程名称：" + Thread.currentThread().getName());
            //解析文章内容内容
            List<Map> mapList = JSON.parseArray(content, Map.class);

            Map dataModel = new HashMap<>();
            dataModel.put("content", mapList);

            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            //数据与模板结合
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);

            //把生成的页面  上传到minio
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String upload = minIOService.upload("article/" + article.getId() + ".html", is, "text/html");
            article.setStaticUrl(upload);
            apArticleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
